require 'libxml'

class CzController < ApplicationController
  def insert_datafield(node, tag)
    node << datafield = LibXML::XML::Node.new("datafield")
    datafield['tag']=tag
    datafield['ind1']=" "
    datafield['ind2']=" "
    datafield
  end

  def insert_subfield(node, code, term)
    node << subfield =LibXML:: XML::Node.new("subfield")
    subfield['code']=code
    subfield.content=term
    subfield
  end

  def insert_controlfield(node, tag, term)
    node << controlfield = LibXML::XML::Node.new("controlfield")
    controlfield['tag']=tag
    controlfield.content=term
    controlfield
  end

  def analyze
    require 'libxml'
    dn ='dn:http://www.loc.gov/MARC21/slim'
    xml_document = LibXML::XML::Document.file('/home/stephan/RSQV/cz.xml')
    if params["extext"]
      rismid=params["extext"]["name"]
    end
    book_xpath = '//dn:record'
    nodes=xml_document.find(book_xpath,dn)
    @countnodes=nodes.size
    @res={}
    nodes.each {|record| record.each {|node|
        node.attributes.each{|att|
          tag=node.attributes[att.name] if att.name=="tag"
          if !@res.key?(tag)
            @res[tag]=[]
          end
          node.children.each{|subf|
            if subf.name=="subfield"
              subf.attributes.each {
                |atts| @res[tag] <<subf.attributes[atts.name] if atts.name=="code" and !@res[tag].include?(subf.attributes[atts.name])
              }
            end
          }
        }
      }
    }
    @endlist=[]
    @res.keys.each{|k| @endlist << k if k}
    @el=@endlist.sort
  end

  def showsubfield
    #@tag='1111'
    #@code='1111'

    #@subfield=""
    if params[:subfield]
      @subfield=params[:subfield]
      @tag=@subfield.split('$')[0]
      @code=@subfield.split('$')[1]
      dn ='dn:http://www.loc.gov/MARC21/slim'
      xml_document = LibXML::XML::Document.file('/home/stephan/RSQV/cz.xml')
      book_xpath = '//dn:record/dn:datafield[@tag="'+String(@tag)+'"]/dn:subfield[@code="'+String(@code)+'"]'
      @nodes=xml_document.find(book_xpath,dn)
      @countno=@nodes.size
    end
  end

  def oconvert
    require 'MarcTools'
    dn ='dn:http://www.loc.gov/MARC21/slim'
    xml_document = LibXML::XML::Document.file('/home/stephan/RSQV/cz.xml')
    book_xpath = '//dn:record'
    @old_xml=xml_document.find(book_xpath,dn)[12]

    converter=MarcTools::MarcConverter.new
    @marc_hash=converter.marc_to_hash(@old_xml)
@marc_hash=converter.updateElements(@marc_hash,'031$a', lambda { |a| a[1..-1]})
@marc_hash=converter.updateElements(@marc_hash,'031$b', lambda { |a| a[1..-1]})
@marc_hash=converter.updateElements(@marc_hash,'031$c', lambda { |a| a[1..-1]})
@marc_hash=converter.updateElements(@marc_hash,'100$a', lambda { |a|  a[-1]==',' ?   a[0..-2] :  a})
@marc_hash=converter.updateElements(@marc_hash,'700$a', lambda  { |a|  a[-1]==',' ?   a[0..-2] :  a})
@marc_hash=converter.updateElements(@marc_hash,'240$a', lambda { |a|  a[-1]==',' ?   a[0..-2] :  a})
@marc_hash=converter.changeTag(@marc_hash,'246', '730') 
@marc_hash=converter.changeTag(@marc_hash,'080', '500')
@marc_hash=converter.changeTag(@marc_hash,'910', '852')
@marc_hash=converter.insertTag(@marc_hash,'852$a', 'CZ-Bu')

    @new_xml=converter.hash_to_marc(@marc_hash)
  end

  def ooldconvert
    require 'MarcConverter'
    dn ='dn:http://www.loc.gov/MARC21/slim'
    xml_document = LibXML::XML::Document.file('/home/stephan/RSQV/cz.xml')
    book_xpath = '//dn:record'
    @doc1=xml_document.find(book_xpath,dn)[0]
    #a=%w[ leader 001 003 005 007 008 031$a 031$b 031$c 100$a 100$d 240$a 245$a ]
    #a=%w[ 031$a 031$b 031$c 100$a  240$a]
    a=%w[ 100$a  240$a]
    converter=MarcConverter::MarcCollection.new
    converter.taglist=a
    converter.taglist.each{|e| converter.insertMarcElement(@doc1,e)}
    @rec=converter.result
    #@build=MarcConverter::MarcBuilder.new(LibXML::XML::Document.new())

    @dub=@rec.map{|e| e.tag.to_s.sub(/\$.*/,"")+e.position.to_s}.uniq
    @sort=@rec.map{|e| [e.tag.to_s.sub(/\$.*/,"")+e.position.to_s, e.tag.to_s.sub(/.*\$/,"")+e.content]}

    @doc=LibXML::XML::Document.new()
    @doc.root = LibXML::XML::Node.new("collection")
    @doc.root << @record=LibXML::XML::Node.new("record")

    @dub.each { |e|
      if e[0..1]=='00'
        @record <<controlfield=LibXML::XML::Node.new("controlfield")
        controlfield['tag']=e[0..-2]

      elsif e=='leader1'
        @record <<leader=LibXML::XML::Node.new("leader")
        leader.content=e[0..-2]
      else
        @record <<datafield=LibXML::XML::Node.new("datafield")
        marker=e
        datafield['tag']=(e[0..-2])

        @sort.each { |e|
          if
          e[0]==marker
            datafield <<subfield=LibXML::XML::Node.new('subfield')
            subfield['code']=e[1][0]
            subfield.content=e[1][1..-1]
          end}
      end}

    #dub<< e.tag.to_s.sub(/\$.*/,"")+e.position.to_s
    #@build.insertSubelement(e.tag, e.content)
    #end

    #@rec.each { |e|
    #if !dub.include?(e.tag.to_s.sub(/\$.*/,"")+e.position.to_s)
    #@build.insertElement(e.tag, e.content)

    #dub<< e.tag.to_s.sub(/\$.*/,"")+e.position.to_s
    #@build.insertSubelement(e.tag, e.content)
    #end
    #           }

    #@build.insertElement('001', '4711')
    #@build.insertElement('100$a', 'Brahms')

  end

  def convert
    rismid="458002040"
    dn ='dn:http://www.loc.gov/MARC21/slim'
    xml_document = LibXML::XML::Document.file('/home/stephan/RSQV/cz.xml')
    if params["extext"]
      rismid=params["extext"]["name"]
    end
    book_xpath = '//dn:record/dn:controlfield[@tag="001"][contains(.,"'+rismid+'")]/..'
    nodes=xml_document.find(book_xpath,dn)
    @ids=xml_document.find('//dn:record/dn:controlfield[@tag="001"]/text()',dn).to_a.shuffle[0..6]
    @archive_node=Array.new
    nodes.each { |e|  @archive_node.push(e.copy(:deep => false))}
    doc = LibXML::XML::Document.new()
    @doc1=doc
    doc.root = LibXML::XML::Node.new("collection")
    #XML::Namespace.new(doc.root, nil, 'http://www.loc.gov/MARC21/slim')

    if nodes.size >= 1
      nodes.each { |item|
        doc.root << record=LibXML::XML::Node.new("record")
        item.find('dn:leader',dn).each {|e| record<<leader=LibXML::XML::Node.new("leader") ;  leader.content=e.content }
        item.find('dn:controlfield[@tag="001"]',dn).each {|e|  insert_controlfield(record, '001', e.content)}
        item.find('dn:controlfield[@tag="003"]',dn).each {|e|  insert_controlfield(record, '003', e.content)}
        item.find('dn:controlfield[@tag="005"]',dn).each {|e|  insert_controlfield(record, '005', e.content)}
        item.find('dn:controlfield[@tag="007"]',dn).each {|e|  insert_controlfield(record, '007', e.content)}
        item.find('dn:controlfield[@tag="008"]',dn).each {|e|  insert_controlfield(record, '008', e.content)}

    
        data={
          '001'=>nil,
          '003'=>nil,
          '005'=>nil,
          '007'=>nil,
          '008'=>nil,
          '028'=>%w[ a d ],
          '031'=>%w[ a b c m g n o p r ],
          '041'=>%w[ a ],
          '047'=>%w[ a ],
          '048'=>%w[ a ],
          '072'=>%w[ a x ],
          '080'=>%w[ 2 a ],
          '100'=>%w[ a d ],
          '240'=>%w[ a m n r ],
          '245'=>%w[ a b c h n p ],
          '246'=>%w[ a ],
          '250'=>%w[ a ],
          '260'=>%w[ a b c ],
          '300'=>%w[ a c e ],
          '500'=>%w[ a ],
          '501'=>%w[ a ],
          '505'=>%w[ a r t ],
          '518'=>%w[ a ],
          '561'=>%w[ a ],
          '567'=>%w[ a ],
          '650'=>%w[ a ],
          '653'=>%w[ a ],
          '655'=>%w[ a ],
          '700'=>%w[ 4 a d ],
          '740'=>%w[ a ],
          '856'=>%w[ 3 u ],
          '910'=>%w[ a b ],
        }
    
        taglist=['leader']
        y=data.keys.sort.each{|k|
          if data[k]
            data[k].sort.each{|v|
              taglist<<k+'$'+v     }
          else
            taglist<<k
          end  }

          
        data={
          #'020'=>%w[ a c ],
          '028'=>%w[ a d ],
          '031'=>%w[ a b c m g n o p r 2 ],
          #'040'=>%w[ a b c ],
          '041'=>%w[ a ],
          '047'=>%w[ a ],
          '048'=>%w[ a ],
          #'072'=>%w[ 2 9 a x ],
          '072'=>%w[ a x ],
          '500<-080'=>%w[ 2 a ],
          #'100'=>%w[ 4 7 a c d ],
          '100'=>%w[ 4 a d ],
          #'240'=>%w[ a m n p r ],
          '240'=>%w[ a m n r ],
          '245'=>%w[ a b c h n p ],
          '730<-246'=>%w[ a ],
          '250'=>%w[ a ],
          #'254'=>%w[ a ],
          '260'=>%w[ a b c ],
          #'300'=>%w[ a b c e ],
          '300'=>%w[ a c e ],
          #'306'=>%w[ a ],
          #'490'=>%w[ a ],
          '500'=>%w[ a ],
          '501'=>%w[ a ],
          '505'=>%w[ a r t ],
          '518'=>%w[ a ],
          #'546'=>%w[ a ],
          '561'=>%w[ a ],
          #'563'=>%w[ a ],
          '567'=>%w[ a ],
          #'568'=>%w[ a ],
          #'580'=>%w[ a ],
          #'600'=>%w[ 2 a ],
          #'610'=>%w[ 2 7 a ],
          #'648'=>%w[ 2 a ],
          #'650'=>%w[ 2 a y z ],
          '650'=>%w[ a ],
          '653'=>%w[ a ],
          #---> AH600T
          #'655'=>%w[ 2 a ],
          '655'=>%w[ a ],
          #'700'=>%w[ 3 4 7 a c d l o p t ],
          '700'=>%w[ 4 a d ],
          '730<-740'=>%w[ a ],
          #'772'=>%w[ t ],
          #'830'=>%w[ a ],
          '856'=>%w[ 3 u ],
          '852<-910'=>%w[ a b ],
          #'964'=>%w[ a x z ],
        }

        data.keys.sort.each {|k|
          tag=k.sub(/.*<-/,"")
          codes=data[k]

          if k=='240'
            items=item.find('dn:datafield[@tag="'+tag+'"]',dn)
            if items.size!=0
              items.each { |e|
                df=insert_datafield(record, tag)
                codes.each {|code| e.find('dn:subfield[@code="'+code+'"]',dn).each {|e|
                    if %w[ a ].include?(code)
                      insert_subfield(df,code, e.content[0..-2])
                    else
                      insert_subfield(df,code, e.content)
                    end}
                }
              }

            else
              df=insert_datafield(record,'240')
              insert_subfield(df, 'a', 'Pieces')
            end

          else
            item.find('dn:datafield[@tag="'+tag+'"]',dn).each { |e|

              if tag=='031'
                df=insert_datafield(record, tag)
                codes.each {|code| e.find('dn:subfield[@code="'+code+'"]',dn).each {|e|
                    if %w[ a b c].include?(code)
                      insert_subfield(df,code, e.content.sub(/\A0/,""))
                    else
                      insert_subfield(df,code, e.content)
                    end}}

              elsif tag=='080'
                df=insert_datafield(record, '500')
                term=[]
                codes.each {|code| e.find('dn:subfield[@code="'+code+'"]',dn).each {|e|
                    term<<e.content    }                                        }
                insert_subfield(df,'a', term.join(" "))

              elsif tag=='100'
                df=insert_datafield(record, tag)
                codes.each {|code| e.find('dn:subfield[@code="'+code+'"]',dn).each {|e|
                    if %w[ a ].include?(code)
                      insert_subfield(df,code, e.content[0..-2])
                    else
                      insert_subfield(df,code, e.content)
                    end}}

              elsif tag=='245'
                df=insert_datafield(record, tag)
                title=[]
                codes.each {|code| e.find('dn:subfield[@code="'+code+'"]',dn).each {|e|
                    if %w[ a b c h n p ].include?(code)
                      title<< e.content
                    else
                      insert_subfield(df,code, e.content)
                    end}
                }
                if title.size >0
                  insert_subfield(df,'a', title.join(" /  "))
                end

              elsif tag=='246'
                df=insert_datafield(record, '730')

                codes.each {|code| e.find('dn:subfield[@code="'+code+'"]',dn).each {|e|
                    insert_subfield(df,code, e.content)   }
                }

              elsif tag=='653'
                df=insert_datafield(record, '650')

                codes.each {|code| e.find('dn:subfield[@code="'+code+'"]',dn).each {|e|
                    insert_subfield(df,code, e.content)   }
                }

              elsif tag=='700'
                df=insert_datafield(record, tag)
                codes.each {|code| e.find('dn:subfield[@code="'+code+'"]',dn).each {|e|
                    if %w[ a ].include?(code)
                      insert_subfield(df,code, e.content[0..-2])
                    else
                      insert_subfield(df,code, e.content)
                    end}}

              elsif tag=='910'
                df=insert_datafield(record, '852')
                codes.each {|code|
                  if code=='a'
                    bib=e.find('dn:subfield[@code="'+code+'"]',dn)
                    if bib.size!=0
                      b.each {|e|
                        insert_subfield(df,code, e.content)
                      }
                    else
                      insert_subfield(df,code, 'CZ-Bu')
                    end
                  else
                    e.find('dn:subfield[@code="'+code+'"]',dn).each {|e|
                      insert_subfield(df,code, e.content)}
                  end
                }

              else
                df=insert_datafield(record, tag)
                codes.each {|code| e.find('dn:subfield[@code="'+code+'"]',dn).each {|e| insert_subfield(df,code, e.content)} }
              end
            }  end
        }

      }
    else
      @node="No result"
    end

  end
end

